#!/usr/bin/env python
import numpy as np
import os, time,socket,sys,json,random
from meas_data import meas_data

sensor="CPU"
pathname = os.path.dirname(sys.argv[0])        
abspath=os.path.abspath(pathname)

idfile=abspath+"/id.json"
id_conf=0
try:
	idf=open(idfile,"r")
	id_conf=json.load(idf)['id']
	idf.close()
except:
	id_conf=0

configfile=abspath+"/config.json"
try:
	cf=open(configfile,"r")
except:
	cf=open(configfile+".template","r")

log_conf=json.load(cf)
cf.close()

parameter={"device":socket.gethostname(),"deviceid":"FF","mean_count":5,"ring_length":300,"wait":0.1,"cycle":20,"check_last":5,"gpg_keyid":"","digits":4,"store_dir":"/home/pi/log/"}
for n in parameter:
  if n in log_conf:
    parameter[n]=log_conf[n]

bsensor=False
if sensor in log_conf:
	if "enable" in log_conf[sensor]:
		if log_conf[sensor]["enable"] == 1:
			bsensor=True

if bsensor:
	parameter["sensor"]=sensor
	if "temperature" in log_conf[sensor]["var_name"]:
		parameter["var_name"]="temperature"
	else:
		bsensor=False

if bsensor:
	cpu_meas=meas_data(parameter)
#	cpu_meas=meas_data(var_name="temperature",ring_length=parameter['ring_length'],device=parameter['device'],sensor="CPU",store_dir="/home/pi/log",digits=4,check_last=parameter['check_last'],id_conf=id_conf,deviceid=parameter['deviceid'])
	cpu_meas.set_sql(host="localhost",port=8080,min_wait=parameter['wait'])
	cpu_meas.set_rsa("25A4CF79414F10FD")

bmqtt=False
if "mqtt" in log_conf:
  bmqtt=True
  lcmq=log_conf['mqtt']
  mbroker=""
  if 'broker' in lcmq:
    mbroker=lcmq['broker']
  else:
    bmqtt=False
  mport=1883
  if 'port' in lcmq:
    mport=lcmq['port']
  if bmqtt:
    cpu_meas.set_mqtt(broker=mbroker,port=mport)

a = 2


while True:
  # get cpu temperature
  cpu_meas.append(int(open('/sys/class/thermal/thermal_zone0/temp').read()))
  
  time.sleep(parameter['wait'])


# close the client

print("done")


